package com.leonzx.base.service;

import com.leonzx.base.dao.RedisDAO;
import com.leonzx.base.utils.RedisConstants;
import com.leonzx.base.utils.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Author:梁亮
 * @Description:
 * @Date: 2018/6/25 15:37
 */
@Service
public class RedisService extends BaseService {
    @Autowired
    private RedisDAO redisDAO;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 缓存shiro信息键值
     */
    private String cacheKey = "shiro:cache:" + RedisConstants.SHIRO_REDIS_CACHE + ":";

    /**
     * 获取在线用户的用户名
     *
     * @return
     */
    public List<String> getOnlineUsernames() {
        Set<String> keys = getLikeValue(cacheKey + "*");
        List<String> usernames = new ArrayList<>();
        for (String key : keys) {
            String username = key.replace(cacheKey, "");
            usernames.add(username);
        }
        //排序
        Collections.sort(usernames, String::compareTo);
        return usernames;
    }

    /**
     * 存入redis
     *
     * @param key
     * @param val
     */
    public void setKey(String key, String val) {
        redisDAO.setKey(key, val);
    }

    /**
     * 存入redis
     *
     * @param key
     * @param val
     * @param timeout  失效时间
     * @param timeUnit 失效时间单位
     */
    public void setKey(String key, String val, long timeout, TimeUnit timeUnit) {
        redisDAO.setKey(key, val, timeout, timeUnit);
    }

    /**
     * 获取key的value
     *
     * @param key
     * @return
     */
    public String getValue(String key) {
        return redisDAO.getValue(key);
    }

    /**
     * @param key
     * @return
     */
    public Set<String> getLikeValue(String key) {
        return redisDAO.likeValue(key);
    }

    public void remove(String key) {
        redisDAO.remve(key);
    }

    /**
     * @param key
     * @return String    返回类型
     * @throws
     * @Title: setToken
     * @Description: 存入令牌
     */
    public String setToken(String key) {
        String uuid = UUIDUtils.getUUID();
        redisTemplate.opsForValue().set(key, uuid);
        return uuid;
    }
}
